<template>
  <div>
    <el-dialog title="编辑单位" :visible.sync="dialogVisible" width="600px" :before-close="closeDialog"
      :close-on-click-modal="false" :append-to-body="true">
      <el-form :model="editForm" :rules="rules" ref="refForm" label-width="110px">

        <el-row>
          <el-col >
            <el-form-item size="small" label="单位名称" prop="orgName">
              <el-input clearable v-model.trim="editForm.orgName" placeholder="请输入名称"
                oninput="value=value.replace(/\s*/g,'')" @blur="editForm.orgName = $event.target.value" maxlength="20">
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item size="small" label="所属国家" prop="homeCountry">
              <el-select clearable filterable v-model='editForm.homeCountry' style="width: 100%;" placeholder='请选择所属国家'>
                <el-option v-for='item in homeCountryList' :label='item.value' :value='item.value' :key='item.value'>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="单位监管类型" prop="flatType">
              <el-select clearable v-model='editForm.flatType' style="width: 100%;" placeholder='请选择单位监管类型'>
                <el-option v-for='item in flatTypeList' :label='item.name' :value='item.id' :key='item.id'>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="small" label="单位性质" prop="nature">
              <el-select clearable v-model='editForm.nature' style="width: 100%;" placeholder='请选择单位性质'>
                <el-option v-for='item in natureList' :label='item.name' :value='item.id' :key='item.id'>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="单位类别" prop="category">
              <el-select clearable v-model='editForm.category' style="width: 100%;" placeholder='请选择单位类别'>
                <el-option v-for='item in categoryList' :label='item.name' :value='item.id' :key='item.id'>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="small" label="监管等级" prop="grade">
              <el-select clearable v-model='editForm.grade' style="width: 100%;" placeholder='请选择监管等级'>
                <el-option v-for='item in gradeList' :label='item.name' :value='item.id' :key='item.id'>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item size="small" label="地区" prop="streetCode">
          <div style="display: flex; align-items: center">

            <el-select v-model="editForm.provinceCode" placeholder="省" @change='changprovince' style="width: 400px">
              <el-option v-for="(item, i) in provinceList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>
            <el-select v-model="editForm.cityCode" placeholder="市" @change='changcity' style="width: 400px">
              <el-option v-for="(item, i) in cityList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>
            <el-select v-model="editForm.areaCode" placeholder="区" @change='changarea' style="width: 400px">
              <el-option v-for="(item, i) in areaList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>
            <el-select v-model="editForm.streetCode" placeholder="街道" @change='changestreet' style="width: 400px">
              <el-option v-for="(item, i) in streetList" :key="i" :label="item.regionName" :value="item.regionCode">
              </el-option>
            </el-select>

            <i class="iconfont zuobiao" style="
                    font-size: 20px;
                    margin-left: 10px;
                    cursor: pointer;
                  " @click="openMap"></i>
          </div>
        </el-form-item>

        <el-form-item size="small" label="详细地址" prop="address">
          <el-input type="textarea" :rows="2" placeholder="详细地址" v-model="editForm.address"
            oninput="value=value.replace(/\s*/g,'')" @blur="editForm.address = $event.target.value" maxlength="30"
            resize='none' :autosize="{ minRows: 2, maxRows: 5 }">
          </el-input>
        </el-form-item>

        <el-form-item size="small" label="社区">
          <el-select v-model='editForm.communityCode' clearable @change='changecommunity' style="width: 100%;"
            placeholder='请选择社区'>
            <el-option v-for="(item, i) in communityList" :key="i" :label="item.regionName" :value="item.regionCode">
            </el-option>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="值班室电话" prop="telephone">
          <el-input oninput="value=value.replace(/[^\d]/g,'')" @blur="editForm.telephone = $event.target.value" clearable
            placeholder="值班室电话" maxlength="11" v-model.trim="editForm.telephone">
          </el-input>
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="small" label="施工单位" prop="construction">
              <el-input oninput="value=value.replace(/\s*/g,'')" @blur="editForm.construction = $event.target.value"
                clearable placeholder="请输入施工单位" maxlength="20" v-model.trim="editForm.construction">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item size="small" label="法人姓名">
              <el-input clearable v-model.trim="editForm.corporateName" placeholder="请输入法人姓名"
                oninput="value=value.replace(/\s*/g,'')" @blur="editForm.corporateName = $event.target.value"
                maxlength="20"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="small" label="法人身份证" prop="corporateIdCard">
              <el-input clearable v-model.trim="editForm.corporateIdCard" placeholder="请输入法人身份证"
                oninput="value=value.replace(/\s*/g,'')" @blur="editForm.corporateIdCard = $event.target.value"
                maxlength="18"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" @click="submit" class="confirm-button">确 定</el-button>
      </span>

      <el-dialog width="50%" title="选择地区" :visible.sync="innerVisible" append-to-body :close-on-click-modal="false">
        <div class="mapLoc" v-if="isShowMap">
          <iframe :src="reqUrl" v-if="isShowMap" frameborder="0" class="iframe" seamless scrolling="no"></iframe>
        </div>
      </el-dialog>

    </el-dialog>

  </div>
</template>
<script>
import { reqOrgEdit, reqRegion, reqRegionLevel } from "@api/api.js";
import mixinRules from "./mixins/rules.js";
import { mapState } from "vuex";
import $ from 'jquery';

export default {
  props: ["editOrgInfo", "getLocationInfo", "getAddressflag"],
  mixins: [mixinRules],
  data() {
    return {
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      communityList: [],//社区
      dialogVisible: false,
      innerVisible: false,
      editForm: {
        id: "",
        orgName: "",
        flatType: "",
        parentId: "0",
        lat: "",
        lng: "",
        province: "",
        provinceCode: "",
        city: "",
        cityCode: "",
        area: "",
        areaCode: "",
        street: "",
        streetCode: "",
        address: "",
        communityCode: "",//社区
        community: "",
        nature: "", // 单位性质
        category: "",
        homeCountry: "",
        grade: "",
        telephone: "",
        corporateName: "",
        corporateIdCard: "",
        construction:""
      },
      reqUrl:
        "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1&coord=112.576927,29.051441",
      isShowMap: false,
      LocationInfo:true,//判断是否从地图选的经纬度
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    getAddressflag() {
      if (!this.dialogVisible) return;
      this.LocationInfo=true;
      this.editForm.lat = this.getLocationInfo.getLat;
      this.editForm.lng = this.getLocationInfo.getLng;
      // 先清空
      this.editForm.province = ''
      this.editForm.provinceCode = ''
      this.editForm.city = ''
      this.editForm.cityCode = ''
      this.editForm.area = ''
      this.editForm.areaCode = ''
      this.editForm.street = ''
      this.editForm.streetCode = ''
      this.editForm.community = ''
      this.editForm.communityCode = ''

      // console.log(this.getLocationInfo);
      this.editForm.province = this.getLocationInfo.province;
      this.editForm.city = this.getLocationInfo.city;
      this.editForm.area = this.getLocationInfo.area;
      this.editForm.street = this.getLocationInfo.street;
      this.editForm.address = this.getLocationInfo.address == "我的位置" ? "" : this.getLocationInfo.address;
      // this.isShowMap = false;
      this.innerVisible = false;
      this.getRegion();
    },
    'editForm.address'(e) {
      if(this.LocationInfo) return;
      this.addrHand()
    },
    'editForm.streetCode'(e) {
      if(this.LocationInfo) return;
      this.addrHand()
    },
    editOrgInfo: {
      handler(val) {
        // console.log(val);
        this.editForm.id = val.id;
        this.editForm.orgName = val.orgName;
        this.editForm.province = val.province;
        this.editForm.lat = val.lat;
        this.editForm.lng = val.lng;
        this.editForm.provinceCode = val.provinceCode;
        this.editForm.city = val.city;
        this.editForm.cityCode = val.cityCode;
        this.editForm.area = val.area;
        this.editForm.areaCode = val.areaCode;
        this.editForm.street = val.street;
        this.editForm.streetCode = val.streetCode;
        this.editForm.community = val.community;
        this.editForm.communityCode = val.communityCode;
        this.editForm.address = val.address;
        this.editForm.flatType = val.flatType;
        this.editForm.nature = val.nature;
        this.editForm.category = val.category;
        this.editForm.homeCountry = val.homeCountry;
        this.editForm.grade = val.grade;
        this.editForm.telephone = val.telephone;
        this.editForm.corporateName = val.corporateName;
        this.editForm.corporateIdCard = val.corporateIdCard;
        this.editForm.construction = val.construction;
      },
      deep: true,
    },
    // getLocationInfo: {
    //   handler(val) {
    //     this.editForm.lat = val.getLat;
    //     this.editForm.lng = val.getLng;
    //     this.editForm.province = val.province;
    //     this.editForm.city = val.city;
    //     this.editForm.area = val.area;
    //     this.editForm.street = val.street;
    //     this.editForm.address = val.address == "我的位置" ? "" : val.address;
    //     // this.isShowMap = false;
    //     this.innerVisible = false;
    //     this.getRegion();
    //   },
    //   deep: true,
    // },
  },
  methods: {
    // 根据省查询市
    async changprovince(val) {
      this.LocationInfo=false;
      this.editForm.address = "";
      this.cityList = [];
      this.editForm.city = "";
      this.editForm.cityCode = "";
      this.areaList = [];
      this.editForm.area = "";
      this.editForm.areaCode = "";
      this.streetList = [];
      this.editForm.street = "";
      this.editForm.streetCode = "";
      this.communityList = []
      this.editForm.community = ''
      this.editForm.communityCode = ''
      const res = await reqRegionLevel(val);
      this.cityList = res.data.rows;
      this.provinceList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.province = item.regionName;
          return;
        }
      });
    },
    // 根据市查询区
    async changcity(val) {
      this.LocationInfo=false;
      this.editForm.address = "";
      this.areaList = [];
      this.editForm.area = "";
      this.editForm.areaCode = "";
      this.streetList = [];
      this.editForm.street = "";
      this.editForm.streetCode = "";
      this.communityList = []
      this.editForm.community = ''
      this.editForm.communityCode = ''
      const res = await reqRegionLevel(val);
      this.areaList = res.data.rows;
      this.cityList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.city = item.regionName;
          return;
        }
      });
    },
    // 根据区查询街道
    async changarea(val) {
      this.LocationInfo=false;
      this.editForm.address = "";
      this.streetList = [];
      this.editForm.street = "";
      this.editForm.streetCode = "";
      this.communityList = []
      this.editForm.community = ''
      this.editForm.communityCode = ''
      const res = await reqRegionLevel(val);
      this.streetList = res.data.rows;
      this.areaList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.area = item.regionName;
          return;
        }
      });
    },
    // 街道名字赋值
    async changestreet(val) {
      this.communityList = []
      this.editForm.community = ''
      this.editForm.communityCode = ''
      const res = await reqRegionLevel(val);
      this.communityList = res.data.rows;
      this.streetList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.street = item.regionName;
          return;
        }
      });
    },
    // 社区名称赋值
    changecommunity(val) {
      this.communityList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.community = item.regionName;
          return;
        }
      });
    },
    // 省市区获取
    openMap() {
      this.isShowMap = true;
      this.reqUrl=
        `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1&coord=${this.editForm.lng},${ this.editForm.lat}`
      this.innerVisible = true;
    },
    // 查询省级行政单位
    async getRegion() {
      const res = await reqRegion();
      res.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.province) {
          this.editForm.provinceCode = item.regionCode; //省行政码
          return;
        }
      });
      this.getRegionLevel();
    },
    // 查询省级下行政单位
    async getRegionLevel() {
      const res = await reqRegionLevel(this.editForm.provinceCode);
      this.cityList = res.data.rows;
      res.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.city) {
          this.editForm.cityCode = item.regionCode; //市行政码
          return;
        }
      });
      // 特殊市辖区查不到  默认选择第一个 
      if (this.editForm.cityCode == '') {
        this.editForm.city = res.data.rows[0].regionName
        this.editForm.cityCode = res.data.rows[0].regionCode
      }

      const res2 = await reqRegionLevel(this.editForm.cityCode);
      this.areaList = res2.data.rows;
      if (this.editForm.area == '') return;//地图中没获取到区级不走下面
      res2.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.area) {
          this.editForm.areaCode = item.regionCode; //区行政码
          return;
        }
      });

      //   if (this.editForm.areaCode == "" || this.editForm.areaCode == null)
      //     return this.$modal.notifyWarning("数据异常，请联系管理员");
      const res3 = await reqRegionLevel(this.editForm.areaCode);
      this.streetList = res3.data.rows;
      if (this.editForm.street == '') return;//地图中没获取到街道不走下面
      res3.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.street) {
          this.editForm.streetCode = item.regionCode; //街道行政码
          return;
        }
      });

      const res4 = await reqRegionLevel(this.editForm.streetCode);
      this.communityList = res4.data.rows;
      if (this.editForm.community == '') return;
      res4.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.community) {
          this.editForm.communityCode = item.regionCode;
          return;
        }
      });

    },

    // 查询省级行政单位
    async RegionList() {
      const res = await reqRegion();
      this.provinceList = res.data.rows;
    },
    // 市
    cityArr() {
      this.$nextTick(async () => {
        if (
          this.editForm.provinceCode == null ||
          this.editForm.provinceCode == ""
        )
          return;
        const res = await reqRegionLevel(this.editForm.provinceCode);
        this.cityList = res.data.rows;
      });
    },

    // 区
    areaArr() {
      this.$nextTick(async () => {
        if (this.editForm.cityCode == null || this.editForm.cityCode == "")
          return;
        const res = await reqRegionLevel(this.editForm.cityCode);
        this.areaList = res.data.rows;
      });
    },

    // 街道
    RegionLevelList() {
      this.$nextTick(async () => {
        if (this.editForm.areaCode == null || this.editForm.areaCode == "")
          return;
        const res = await reqRegionLevel(this.editForm.areaCode);
        this.streetList = res.data.rows;
      });
    },

    // 社区
    communitylList() {
      this.$nextTick(async () => {
        if (this.editForm.streetCode == null || this.editForm.streetCode == "")
          return;
        const res = await reqRegionLevel(this.editForm.streetCode);
        this.communityList = res.data.rows;
      });
    },

    // 点击编辑
    submit() {
      this.$refs.refForm.validate(async (valid) => {
        //  this.$modal.notifyWarning("请检查输入信息是否有误");
        if (!valid) return;
        let {
          id,
          orgName,
          lat,
          lng,
          province,
          provinceCode,
          city,
          cityCode,
          area,
          areaCode,
          street,
          streetCode,
          community,
          communityCode,
          address,
          flatType,
          nature, // 单位性质
          category,
          homeCountry,
          grade,
          telephone,
          corporateName,
          corporateIdCard,
          construction
        } = this.editForm;
        if (!streetCode) return this.$modal.notifyWarning("请选择地区");
        let params = {
          id,
          tenantId: this.user.tenantId,
          orgName,
          lat,
          lng,
          province,
          provinceCode,
          city,
          cityCode,
          area,
          areaCode,
          street,
          streetCode,
          community,
          communityCode,
          address,
          flatType,
          nature, // 单位性质
          category,
          homeCountry,
          grade,
          telephone,
          corporateName,
          corporateIdCard,
          construction
        };
        const res = await reqOrgEdit(params);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("编辑成功");
        this.closeDialog();
        this.$parent.getInitDataList();
      });
    },
    //地址转经纬度
    addrHand() {
      let that = this
      // console.log(that.editForm.province + that.editForm.city + that.editForm.area + that.editForm.address);
      $.ajax({
        type: "get",
        dataType: 'jsonp',
        data: {
          key: "44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53", // 填申请到的腾讯key
          address: that.editForm.province + that.editForm.city + that.editForm.area + that.editForm.street +that.editForm.address, //具体的地址
          output: 'jsonp' //返回格式：支持JSON/JSONP，默认JSON
        },
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: "https://apis.map.qq.com/ws/geocoder/v1/?",
        success: function (json) {
          // console.log(json)
          if (json.status == 0) {
            that.editForm.lng = json.result.location.lng
            that.editForm.lat = json.result.location.lat
            // console.log(that.editForm.lat);
            // console.log(that.editForm.lng);
            // that.$message({
            //   message: '成功获取位置的经纬度',
            //   type: 'success'
            // })
          } else {
            // that.$message.error('获取该位置经纬度失败')
          }
        },
        error: function (err) {
          // that.$message.error('异常错误，请刷新浏览器后重试')
        }
      })
    },
    // 点击关闭弹框
    closeDialog() {
      this.$refs.refForm.resetFields();
      this.dialogVisible = false;
      this.areaList = [];
      this.streetList = [];
      this.cityList = [];
      this.communityList = [];
        this.editForm= {
        id: "",
        orgName: "",
        flatType: "",
        parentId: "0",
        lat: "",
        lng: "",
        province: "",
        provinceCode: "",
        city: "",
        cityCode: "",
        area: "",
        areaCode: "",
        street: "",
        streetCode: "",
        address: "",
        communityCode: "",//社区
        community: "",
        nature: "", // 单位性质
        category: "",
        homeCountry: "",
        grade: "",
        telephone: "",
        corporateName: "",
        corporateIdCard: "",
        construction:""
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

.mapLoc {
  // height: 100vh;
  // width: 100vw;
  // position: fixed;
  // z-index: 9999;
  // top: 0;
  // left: 0;

  height: 60vh;
  width: 100%;
  overflow-y: hidden;

  .iframe {
    width: 100%;
    height: 100%;
  }
}

.zuobiao {
  color: @primaryTxtcolor;
}

// ::v-deep .el-textarea__inner {
//   color: #ececed !important;
// }
// 省市区/
::v-deep .el-input.is-disabled .el-input__inner {
  border-color: @primaryBorderColor !important;
}
</style>